"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
  ArrowLeft,
  Globe,
  Palette,
  Layout,
  Image,
  Type,
  Smartphone,
  Monitor,
  Tablet,
  Eye,
  Download,
  Share2,
  CheckCircle,
  Star,
  Zap,
  Rocket,
  Building,
  ShoppingCart,
  Users,
  FileText,
  Camera,
  Settings,
  Code,
  Brush,
  MousePointer,
  Shield,
  Search,
  BarChart3,
  MessageSquare,
  Mail,
  Phone,
  MapPin,
  Facebook,
  Twitter,
  Instagram,
  Linkedin,
  Youtube,
  Play,
  Edit,
  Save,
  Upload,
  Plus,
  Minus,
  Copy,
  Trash2,
  RefreshCw,
  ExternalLink,
  Calendar,
  Clock,
  Award,
  Target,
  TrendingUp,
  Heart,
  ThumbsUp,
  BookOpen,
  Lightbulb,
  Gift,
  Music,
  Video,
  Headphones,
  Coffee,
  Home,
  Car,
  Plane,
  Utensils,
  Shirt,
  Flower,
  Leaf,
  Sun,
  Moon,
  Sparkles,
  Diamond,
  Gem,
  Compass,
  Map,
  Flag,
  Navigation,
  ChevronLeft,
  ChevronRight,
  Archive,
  PieChart,
  Briefcase
} from "lucide-react"

interface Template {
  id: string
  name: string
  category: string
  preview: string
  features: string[]
  industry: string[]
  price: string
  rating: number
  downloads: number
  description: string
  colors: string[]
  responsive: boolean
  seoOptimized: boolean
  customizable: boolean
}

interface WebsiteData {
  template: Template | null
  companyInfo: {
    name: string
    tagline: string
    description: string
    logo: string
    industry: string
    defaultProductImage?: string
    defaultNewsImage?: string
    defaultHeroImage?: string
    contact: {
      email: string
      phone: string
      address: string
      website: string
    }
    social: {
      facebook: string
      twitter: string
      instagram: string
      linkedin: string
    }
  }
  content: {
    heroTitle: string
    heroSubtitle: string
    heroImages: string[]
    aboutUs: string
    services: Array<{
      title: string
      description: string
      icon: string
    }>
    products: Array<{
      name: string
      description: string
      price: string
      image: string
      features: string[]
    }>
    news: Array<{
      title: string
      content: string
      date: string
      author: string
      category: string
      image: string
    }>
    testimonials: Array<{
      name: string
      position: string
      content: string
      rating: number
    }>
    portfolio: Array<{
      title: string
      description: string
      image: string
      category: string
    }>
  }
  design: {
    primaryColor: string
    secondaryColor: string
    fontFamily: string
    layoutStyle: string
  }
  features: string[]
}

export default function WebsiteBuilderPage() {
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(1)
  const [loading, setLoading] = useState(false)
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null)
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [websiteData, setWebsiteData] = useState<WebsiteData>({
    template: null,
    companyInfo: {
      name: "",
      tagline: "",
      description: "",
      logo: "",
      industry: "",
      defaultProductImage: "",
      defaultNewsImage: "",
      defaultHeroImage: "",
      contact: {
        email: "",
        phone: "",
        address: "",
        website: ""
      },
      social: {
        facebook: "",
        twitter: "",
        instagram: "",
        linkedin: ""
      }
    },
    content: {
      heroTitle: "",
      heroSubtitle: "",
      heroImages: [],
      aboutUs: "",
      services: [],
      products: [],
      news: [],
      testimonials: [],
      portfolio: []
    },
    design: {
      primaryColor: "#3B82F6",
      secondaryColor: "#10B981",
      fontFamily: "Inter",
      layoutStyle: "modern"
    },
    features: []
  })
  const [previewMode, setPreviewMode] = useState("desktop")
  const [publishedUrl, setPublishedUrl] = useState("")

  const templates: Template[] = [
    {
      id: "modern-business",
      name: "现代商务",
      category: "商务",
      preview: "/api/placeholder/400/300",
      features: ["响应式设计", "SEO优化", "快速加载", "联系表单"],
      industry: ["科技", "咨询", "金融", "教育"],
      price: "免费",
      rating: 4.8,
      downloads: 15420,
      description: "专为现代企业设计的简洁专业模板，适合科技公司、咨询机构等",
      colors: ["#3B82F6", "#1E40AF", "#F8FAFC", "#64748B"],
      responsive: true,
      seoOptimized: true,
      customizable: true
    },
    {
      id: "creative-portfolio",
      name: "创意作品集",
      category: "作品集",
      preview: "/api/placeholder/400/300",
      features: ["图片画廊", "视频支持", "动画效果", "作品展示"],
      industry: ["设计", "摄影", "艺术", "创意"],
      price: "¥299",
      rating: 4.9,
      downloads: 12850,
      description: "展示创意作品的理想选择，支持多媒体内容展示",
      colors: ["#8B5CF6", "#A855F7", "#F3E8FF", "#1F2937"],
      responsive: true,
      seoOptimized: true,
      customizable: true
    },
    {
      id: "ecommerce-store",
      name: "电商商店",
      category: "电商",
      preview: "/api/placeholder/400/300",
      features: ["产品展示", "购物车", "支付集成", "库存管理"],
      industry: ["零售", "电商", "时尚", "数码"],
      price: "¥599",
      rating: 4.7,
      downloads: 9634,
      description: "功能完整的电商网站模板，包含购物车和支付功能",
      colors: ["#10B981", "#059669", "#D1FAE5", "#374151"],
      responsive: true,
      seoOptimized: true,
      customizable: true
    },
    {
      id: "restaurant-cafe",
      name: "餐厅咖啡",
      category: "餐饮",
      preview: "/api/placeholder/400/300",
      features: ["菜单展示", "在线预订", "位置地图", "评价展示"],
      industry: ["餐饮", "咖啡", "酒店", "娱乐"],
      price: "¥399",
      rating: 4.6,
      downloads: 7892,
      description: "专为餐饮行业设计，包含菜单、预订等功能",
      colors: ["#F59E0B", "#D97706", "#FEF3C7", "#1F2937"],
      responsive: true,
      seoOptimized: true,
      customizable: true
    },
    {
      id: "healthcare-medical",
      name: "医疗健康",
      category: "医疗",
      preview: "/api/placeholder/400/300",
      features: ["在线预约", "医生介绍", "服务展示", "健康资讯"],
      industry: ["医疗", "健康", "美容", "保健"],
      price: "¥499",
      rating: 4.8,
      downloads: 6543,
      description: "专业的医疗健康网站模板，符合行业标准",
      colors: ["#06B6D4", "#0891B2", "#CFFAFE", "#374151"],
      responsive: true,
      seoOptimized: true,
      customizable: true
    },
    {
      id: "startup-tech",
      name: "科技创业",
      category: "科技",
      preview: "/api/placeholder/400/300",
      features: ["产品介绍", "团队展示", "投资者关系", "博客系统"],
      industry: ["科技", "创业", "SaaS", "AI"],
      price: "¥399",
      rating: 4.9,
      downloads: 11234,
      description: "为科技创业公司量身定制的现代化模板",
      colors: ["#7C3AED", "#5B21B6", "#EDE9FE", "#1F2937"],
      responsive: true,
      seoOptimized: true,
      customizable: true
    }
  ]

  const steps = [
    { id: 1, title: "选择模板", desc: "挑选适合的网站模板" },
    { id: 2, title: "公司信息", desc: "填写基本公司信息" },
    { id: 3, title: "内容编辑", desc: "添加网站内容" },
    { id: 4, title: "设计定制", desc: "个性化设计调整" },
    { id: 5, title: "预览发布", desc: "预览并发布网站" }
  ]

  const industries = [
    "科技/互联网", "电商/零售", "金融服务", "教育培训", 
    "医疗健康", "制造业", "餐饮服务", "文化娱乐",
    "房地产", "交通物流", "设计创意", "其他"
  ]

  const fontFamilies = [
    { name: "Inter", display: "Inter" },
    { name: "Roboto", display: "Roboto" },
    { name: "Poppins", display: "Poppins" },
    { name: "Open Sans", display: "Open Sans" },
    { name: "Lato", display: "Lato" },
    { name: "Montserrat", display: "Montserrat" }
  ]

  const layoutStyles = [
    { id: "modern", name: "现代简约", icon: Layout },
    { id: "classic", name: "经典商务", icon: Building },
    { id: "creative", name: "创意设计", icon: Palette },
    { id: "minimal", name: "极简风格", icon: Minus }
  ]

  const handleTemplateSelect = (template: Template) => {
    setSelectedTemplate(template)
    setWebsiteData(prev => ({
      ...prev,
      template,
      design: {
        ...prev.design,
        primaryColor: template.colors[0],
        secondaryColor: template.colors[1]
      }
    }))
  }

  const updateCompanyInfo = (field: string, value: string) => {
    setWebsiteData(prev => ({
      ...prev,
      companyInfo: {
        ...prev.companyInfo,
        [field]: value
      }
    }))
  }

  const updateContactInfo = (field: string, value: string) => {
    setWebsiteData(prev => ({
      ...prev,
      companyInfo: {
        ...prev.companyInfo,
        contact: {
          ...prev.companyInfo.contact,
          [field]: value
        }
      }
    }))
  }

  const updateSocialInfo = (field: string, value: string) => {
    setWebsiteData(prev => ({
      ...prev,
      companyInfo: {
        ...prev.companyInfo,
        social: {
          ...prev.companyInfo.social,
          [field]: value
        }
      }
    }))
  }

  const updateContent = (field: string, value: any) => {
    setWebsiteData(prev => ({
      ...prev,
      content: {
        ...prev.content,
        [field]: value
      }
    }))
  }

  const updateDesign = (field: string, value: string) => {
    setWebsiteData(prev => ({
      ...prev,
      design: {
        ...prev.design,
        [field]: value
      }
    }))
  }

  const addService = () => {
    const newService = {
      title: "",
      description: "",
      icon: "Star"
    }
    updateContent("services", [...websiteData.content.services, newService])
  }

  const updateService = (index: number, field: string, value: string) => {
    const updatedServices = [...websiteData.content.services]
    updatedServices[index] = { ...updatedServices[index], [field]: value }
    updateContent("services", updatedServices)
  }

  const removeService = (index: number) => {
    const updatedServices = websiteData.content.services.filter((_, i) => i !== index)
    updateContent("services", updatedServices)
  }

  const addProduct = () => {
    const newProduct = {
      name: "",
      description: "",
      price: "",
      image: "/api/placeholder/300/200",
      features: []
    }
    updateContent("products", [...websiteData.content.products, newProduct])
  }

  const updateProduct = (index: number, field: string, value: any) => {
    const updatedProducts = [...websiteData.content.products]
    updatedProducts[index] = { ...updatedProducts[index], [field]: value }
    updateContent("products", updatedProducts)
  }

  const removeProduct = (index: number) => {
    const updatedProducts = websiteData.content.products.filter((_, i) => i !== index)
    updateContent("products", updatedProducts)
  }

  const addNews = () => {
    const newNews = {
      title: "",
      content: "",
      date: new Date().toISOString().split('T')[0],
      author: websiteData.companyInfo.name || "管理员",
      category: "公司动态",
      image: "/api/placeholder/400/200"
    }
    updateContent("news", [...websiteData.content.news, newNews])
  }

  const updateNews = (index: number, field: string, value: string) => {
    const updatedNews = [...websiteData.content.news]
    updatedNews[index] = { ...updatedNews[index], [field]: value }
    updateContent("news", updatedNews)
  }

  const removeNews = (index: number) => {
    const updatedNews = websiteData.content.news.filter((_, i) => i !== index)
    updateContent("news", updatedNews)
  }

  const addHeroImage = () => {
    const newImages = [...websiteData.content.heroImages, "/api/placeholder/800/400"]
    updateContent("heroImages", newImages)
  }

  const removeHeroImage = (index: number) => {
    const newImages = websiteData.content.heroImages.filter((_, i) => i !== index)
    updateContent("heroImages", newImages)
  }

  const validateStep = (step: number) => {
    switch (step) {
      case 1:
        return selectedTemplate !== null
      case 2:
        return websiteData.companyInfo.name && websiteData.companyInfo.industry
      case 3:
        return websiteData.content.heroTitle
      case 4:
        return true
      default:
        return false
    }
  }

  const nextStep = () => {
    if (validateStep(currentStep) && currentStep < 5) {
      setCurrentStep(currentStep + 1)
    }
  }

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1)
    }
  }

  const generateWebsite = async () => {
    setLoading(true)
    // 模拟生成过程
    setTimeout(() => {
      setLoading(false)
      setCurrentStep(5)
    }, 3000)
  }

  const publishWebsite = async () => {
    setLoading(true)
    // 模拟发布过程
    setTimeout(() => {
      const randomId = Math.random().toString(36).substr(2, 9)
      const companyName = websiteData.companyInfo.name || 'mywebsite'
      const url = `https://${companyName.toLowerCase().replace(/\s+/g, '-')}-${randomId}.webbuilder.com`
      setPublishedUrl(url)
      setLoading(false)
      
      // 更好的成功提示
      const message = `🎉 网站发布成功！\n\n网站地址：${url}\n\n您的网站已经上线，可以分享给客户了！`
      alert(message)
    }, 2000)
  }

  const downloadWebsite = () => {
    // 生成HTML代码
    const htmlCode = generateHTMLCode()
    const blob = new Blob([htmlCode], { type: 'text/html' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${websiteData.companyInfo.name || 'website'}.html`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const sharePreview = () => {
    try {
      // Use encodeURIComponent to handle Unicode characters properly
      const previewData = encodeURIComponent(JSON.stringify(websiteData))
      const shareUrl = `${window.location.origin}/preview/${previewData}`
      navigator.clipboard.writeText(shareUrl)
      
      const message = `📋 预览链接已复制到剪贴板！\n\n您可以将此链接分享给客户或同事，\n让他们预览您的网站效果。\n\n链接长度：${shareUrl.length} 字符`
      alert(message)
    } catch (error) {
      console.error('分享预览失败:', error)
      alert('❌ 分享预览失败，请稍后重试\n\n可能的原因：数据过大或网络问题')
    }
  }

  // 检查用户登录状态
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    setCurrentUser(JSON.parse(user))
    setIsLoading(false)
  }, [router])

  const generateHTMLCode = () => {
    const { companyInfo, content, design } = websiteData
    
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${companyInfo.name}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: '${design.fontFamily}', sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }
        header { background: ${design.primaryColor}; color: white; padding: 1rem 0; }
        nav { display: flex; justify-content: space-between; align-items: center; }
        .logo { font-size: 1.5rem; font-weight: bold; }
        .nav-links { display: flex; list-style: none; gap: 2rem; }
        .nav-links a { color: white; text-decoration: none; }
        .hero { background: linear-gradient(135deg, ${design.primaryColor}, ${design.secondaryColor}); color: white; padding: 4rem 0; text-align: center; }
        .hero h1 { font-size: 3rem; margin-bottom: 1rem; }
        .hero p { font-size: 1.2rem; margin-bottom: 2rem; }
        .btn { background: ${design.secondaryColor}; color: white; padding: 12px 24px; border: none; border-radius: 5px; cursor: pointer; }
        .carousel { position: relative; height: 400px; overflow: hidden; margin: 2rem 0; }
        .carousel img { width: 100%; height: 100%; object-fit: cover; }
        .section { padding: 4rem 0; }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 2rem; }
        .card { background: white; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); padding: 2rem; }
        .products .grid { grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); }
        .product-card img { width: 100%; height: 200px; object-fit: cover; border-radius: 5px; margin-bottom: 1rem; }
        .news .grid { grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); }
        .news-card img { width: 100%; height: 150px; object-fit: cover; border-radius: 5px; margin-bottom: 1rem; }
        .news-meta { color: #666; font-size: 0.9rem; margin-bottom: 0.5rem; }
        footer { background: #333; color: white; padding: 2rem 0; text-align: center; }
        .social-links { display: flex; gap: 1rem; justify-content: center; margin-top: 1rem; }
        .social-links a { color: white; }
        @media (max-width: 768px) {
            .hero h1 { font-size: 2rem; }
            .grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <nav>
                <div class="logo">${companyInfo.name}</div>
                <ul class="nav-links">
                    <li><a href="#home">首页</a></li>
                    <li><a href="#about">关于我们</a></li>
                    <li><a href="#services">服务</a></li>
                    <li><a href="#products">产品</a></li>
                    <li><a href="#news">新闻</a></li>
                    <li><a href="#contact">联系我们</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <section id="home" class="hero">
        <div class="container">
            <h1>${content.heroTitle || companyInfo.name}</h1>
            <p>${content.heroSubtitle || companyInfo.tagline}</p>
            <button class="btn">了解更多</button>
        </div>
    </section>

    ${content.heroImages.length > 0 ? `
    <section class="carousel">
        <div class="container">
            ${content.heroImages.map(img => `<img src="${img || companyInfo.defaultHeroImage || 'https://via.placeholder.com/1200x600?text=轮播图片'}" alt="轮播图">`).join('')}
        </div>
    </section>
    ` : ''}

    <section id="about" class="section">
        <div class="container">
            <h2>关于我们</h2>
            <p>${content.aboutUs || companyInfo.description}</p>
        </div>
    </section>

    ${content.services.length > 0 ? `
    <section id="services" class="section">
        <div class="container">
            <h2>我们的服务</h2>
            <div class="grid">
                ${content.services.map(service => `
                    <div class="card">
                        <h3>${service.title}</h3>
                        <p>${service.description}</p>
                    </div>
                `).join('')}
            </div>
        </div>
    </section>
    ` : ''}

    ${content.products.length > 0 ? `
    <section id="products" class="section products">
        <div class="container">
            <h2>我们的产品</h2>
            <div class="grid">
                ${content.products.map(product => `
                    <div class="card product-card">
                        <img src="${product.image || companyInfo.defaultProductImage || 'https://via.placeholder.com/400x300?text=产品图片'}" alt="${product.name}">
                        <h3>${product.name}</h3>
                        <p>${product.description}</p>
                        <div class="price" style="color: ${design.primaryColor}; font-weight: bold; font-size: 1.2rem;">${product.price}</div>
                    </div>
                `).join('')}
            </div>
        </div>
    </section>
    ` : ''}

    ${content.news.length > 0 ? `
    <section id="news" class="section news">
        <div class="container">
            <h2>最新动态</h2>
            <div class="grid">
                ${content.news.map(news => `
                    <div class="card news-card">
                        <img src="${news.image || companyInfo.defaultNewsImage || 'https://via.placeholder.com/600x300?text=新闻图片'}" alt="${news.title}">
                        <div class="news-meta">${news.date} | ${news.author} | ${news.category}</div>
                        <h3>${news.title}</h3>
                        <p>${news.content.substring(0, 100)}...</p>
                    </div>
                `).join('')}
            </div>
        </div>
    </section>
    ` : ''}

    <footer id="contact">
        <div class="container">
            <h3>联系我们</h3>
            <p>邮箱: ${companyInfo.contact.email}</p>
            <p>电话: ${companyInfo.contact.phone}</p>
            <p>地址: ${companyInfo.contact.address}</p>
            <div class="social-links">
                ${companyInfo.social.facebook ? `<a href="${companyInfo.social.facebook}">Facebook</a>` : ''}
                ${companyInfo.social.twitter ? `<a href="${companyInfo.social.twitter}">Twitter</a>` : ''}
                ${companyInfo.social.instagram ? `<a href="${companyInfo.social.instagram}">Instagram</a>` : ''}
                ${companyInfo.social.linkedin ? `<a href="${companyInfo.social.linkedin}">LinkedIn</a>` : ''}
            </div>
            <p style="margin-top: 2rem;">&copy; 2024 ${companyInfo.name}. 保留所有权利。</p>
        </div>
    </footer>
</body>
</html>`
  }

  const WebsitePreview = () => {
    const { companyInfo, content, design } = websiteData
    
    return (
      <div className={`${previewMode === 'mobile' ? 'max-w-sm' : previewMode === 'tablet' ? 'max-w-2xl' : 'w-full'} mx-auto bg-white shadow-lg rounded-lg overflow-hidden`}>
        {/* Header */}
        <header style={{ backgroundColor: design.primaryColor }} className="text-white p-4">
          <div className="flex justify-between items-center">
            <div className="text-xl font-bold">{companyInfo.name || "您的公司"}</div>
            <nav className="hidden md:flex space-x-6">
              <a href="#" className="hover:text-gray-200">首页</a>
              <a href="#" className="hover:text-gray-200">关于我们</a>
              <a href="#" className="hover:text-gray-200">服务</a>
              <a href="#" className="hover:text-gray-200">产品</a>
              <a href="#" className="hover:text-gray-200">新闻</a>
              <a href="#" className="hover:text-gray-200">联系我们</a>
            </nav>
          </div>
        </header>

        {/* Hero Banner */}
        <section style={{ 
          background: `linear-gradient(135deg, ${design.primaryColor}, ${design.secondaryColor})` 
        }} className="text-white p-8 text-center">
          <h1 className="text-3xl md:text-4xl font-bold mb-4">
            {content.heroTitle || companyInfo.name || "欢迎来到我们的网站"}
          </h1>
          <p className="text-lg mb-6">
            {content.heroSubtitle || companyInfo.tagline || "专业、可靠、值得信赖的合作伙伴"}
          </p>
          <button 
            style={{ backgroundColor: design.secondaryColor }}
            className="px-6 py-3 rounded-lg font-medium hover:opacity-90 transition-opacity"
          >
            了解更多
          </button>
        </section>

        {/* Hero Images Carousel */}
        {content.heroImages.length > 0 && (
          <section className="relative h-64 bg-gray-100 overflow-hidden">
            <div className="flex items-center justify-center h-full">
              {content.heroImages.length > 0 ? (
                <div className="relative w-full h-full">
                  <img 
                    src={content.heroImages[0] || companyInfo.defaultHeroImage || "https://via.placeholder.com/1200x600?text=轮播图片"} 
                    alt="轮播图" 
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      e.currentTarget.src = "https://via.placeholder.com/1200x600?text=轮播图片"
                    }}
                  />
                  <div className="absolute inset-0 bg-black bg-opacity-20 flex items-center justify-between px-4">
                    <ChevronLeft className="text-white w-8 h-8 cursor-pointer" />
                    <ChevronRight className="text-white w-8 h-8 cursor-pointer" />
                  </div>
                  <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2">
                    {content.heroImages.map((_, index) => (
                      <div key={index} className="w-2 h-2 bg-white rounded-full opacity-50"></div>
                    ))}
                  </div>
                </div>
              ) : (
                <div className="text-gray-500">暂无轮播图片</div>
              )}
            </div>
          </section>
        )}

        {/* About Section */}
        <section className="p-8">
          <h2 className="text-2xl font-bold mb-4" style={{ color: design.primaryColor }}>
            关于我们
          </h2>
          <p className="text-gray-600 leading-relaxed">
            {content.aboutUs || companyInfo.description || "我们是一家专业的公司，致力于为客户提供优质的产品和服务。"}
          </p>
        </section>

        {/* Services Section */}
        {content.services.length > 0 && (
          <section className="p-8 bg-gray-50">
            <h2 className="text-2xl font-bold mb-6" style={{ color: design.primaryColor }}>
              我们的服务
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {content.services.map((service, index) => (
                <div key={index} className="bg-white p-6 rounded-lg shadow-sm">
                  <div className="w-12 h-12 rounded-lg mb-4 flex items-center justify-center" 
                       style={{ backgroundColor: `${design.primaryColor}20` }}>
                    <Star className="w-6 h-6" style={{ color: design.primaryColor }} />
                  </div>
                  <h3 className="font-semibold mb-2">{service.title || "服务标题"}</h3>
                  <p className="text-gray-600 text-sm">{service.description || "服务描述"}</p>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* Products Section */}
        {content.products.length > 0 && (
          <section className="p-8">
            <h2 className="text-2xl font-bold mb-6" style={{ color: design.primaryColor }}>
              我们的产品
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {content.products.map((product, index) => (
                <div key={index} className="bg-white border rounded-lg overflow-hidden shadow-sm">
                  <img 
                    src={product.image || companyInfo.defaultProductImage || "https://via.placeholder.com/400x300?text=产品图片"} 
                    alt={product.name}
                    className="w-full h-48 object-cover"
                    onError={(e) => {
                      e.currentTarget.src = "https://via.placeholder.com/400x300?text=产品图片"
                    }}
                  />
                  <div className="p-4">
                    <h3 className="font-semibold mb-2">{product.name || "产品名称"}</h3>
                    <p className="text-gray-600 text-sm mb-3">{product.description || "产品描述"}</p>
                    <div className="flex justify-between items-center">
                      <span className="text-lg font-bold" style={{ color: design.primaryColor }}>
                        {product.price || "¥999"}
                      </span>
                      <button 
                        className="px-4 py-2 text-sm rounded"
                        style={{ backgroundColor: design.primaryColor, color: 'white' }}
                      >
                        查看详情
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* News Section */}
        {content.news.length > 0 && (
          <section className="p-8 bg-gray-50">
            <h2 className="text-2xl font-bold mb-6" style={{ color: design.primaryColor }}>
              最新动态
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {content.news.map((news, index) => (
                <div key={index} className="bg-white rounded-lg overflow-hidden shadow-sm">
                  <img 
                    src={news.image || companyInfo.defaultNewsImage || "https://via.placeholder.com/600x300?text=新闻图片"} 
                    alt={news.title}
                    className="w-full h-32 object-cover"
                    onError={(e) => {
                      e.currentTarget.src = "https://via.placeholder.com/600x300?text=新闻图片"
                    }}
                  />
                  <div className="p-4">
                    <div className="text-xs text-gray-500 mb-2">
                      {news.date} | {news.author} | {news.category}
                    </div>
                    <h3 className="font-semibold mb-2 line-clamp-2">{news.title || "新闻标题"}</h3>
                    <p className="text-gray-600 text-sm line-clamp-3">
                      {news.content || "新闻内容摘要..."}
                    </p>
                    <button className="mt-3 text-sm" style={{ color: design.primaryColor }}>
                      阅读全文 →
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* Footer */}
        <footer className="bg-gray-800 text-white p-8">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <div>
              <h3 className="font-bold mb-4">{companyInfo.name || "您的公司"}</h3>
              <p className="text-gray-300 text-sm">{companyInfo.description || "公司简介"}</p>
            </div>
            <div>
              <h3 className="font-bold mb-4">联系我们</h3>
              <div className="space-y-2 text-sm text-gray-300">
                <div className="flex items-center space-x-2">
                  <Mail className="w-4 h-4" />
                  <span>{companyInfo.contact.email || "contact@company.com"}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <Phone className="w-4 h-4" />
                  <span>{companyInfo.contact.phone || "400-000-0000"}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <MapPin className="w-4 h-4" />
                  <span>{companyInfo.contact.address || "公司地址"}</span>
                </div>
              </div>
            </div>
            <div>
              <h3 className="font-bold mb-4">关注我们</h3>
              <div className="flex space-x-4">
                {companyInfo.social.facebook && <Facebook className="w-5 h-5 cursor-pointer" />}
                {companyInfo.social.twitter && <Twitter className="w-5 h-5 cursor-pointer" />}
                {companyInfo.social.instagram && <Instagram className="w-5 h-5 cursor-pointer" />}
                {companyInfo.social.linkedin && <Linkedin className="w-5 h-5 cursor-pointer" />}
              </div>
            </div>
          </div>
          <div className="border-t border-gray-700 mt-8 pt-8 text-center text-sm text-gray-400">
            <p>&copy; 2024 {companyInfo.name || "您的公司"}. 保留所有权利。</p>
          </div>
        </footer>
      </div>
    )
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">验证登录状态...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-6xl mx-auto">
          <Button
            variant="ghost"
            className="mb-6"
            onClick={() => router.push("/")}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回首页
          </Button>

          <div className="flex items-center gap-3 mb-8">
            <div className="p-2 bg-blue-500 text-white rounded-lg">
              <Globe className="h-6 w-6" />
            </div>
            <div>
              <h1 className="text-3xl font-bold">网站模板建站</h1>
              <p className="text-gray-600">快速创建专业的企业网站</p>
            </div>
          </div>

          {/* Progress */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-4">
              {steps.map((step, index) => (
                <div key={step.id} className="flex items-center">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                    currentStep >= step.id 
                      ? 'bg-blue-500 text-white' 
                      : 'bg-gray-200 text-gray-600'
                  }`}>
                    {currentStep > step.id ? <CheckCircle className="h-4 w-4" /> : step.id}
                  </div>
                  {index < steps.length - 1 && (
                    <div className={`w-16 h-1 mx-2 ${
                      currentStep > step.id ? 'bg-blue-500' : 'bg-gray-200'
                    }`} />
                  )}
                </div>
              ))}
            </div>
            <div className="text-center">
              <h2 className="text-xl font-semibold mb-1">{steps[currentStep - 1].title}</h2>
              <p className="text-gray-600">{steps[currentStep - 1].desc}</p>
            </div>
          </div>

          {/* Step 1: 选择模板 */}
          {currentStep === 1 && (
            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>选择网站模板</CardTitle>
                  <p className="text-sm text-gray-600">选择最适合您行业的专业模板</p>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {templates.map((template) => (
                      <Card 
                        key={template.id} 
                        className={`cursor-pointer transition-all hover:shadow-lg ${
                          selectedTemplate?.id === template.id ? 'ring-2 ring-blue-500 bg-blue-50' : ''
                        }`}
                        onClick={() => handleTemplateSelect(template)}
                      >
                        <CardContent className="p-4">
                          <div className="aspect-video bg-gray-200 rounded-lg mb-3 overflow-hidden">
                            <img 
                              src={template.preview} 
                              alt={template.name}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <div className="flex items-center justify-between mb-2">
                            <h3 className="font-semibold">{template.name}</h3>
                            <Badge variant={template.price === "免费" ? "default" : "secondary"}>
                              {template.price}
                            </Badge>
                          </div>
                          <p className="text-sm text-gray-600 mb-3">{template.description}</p>
                          <div className="flex items-center justify-between text-sm">
                            <div className="flex items-center gap-1">
                              <Star className="h-4 w-4 text-yellow-500 fill-current" />
                              <span>{template.rating}</span>
                            </div>
                            <span className="text-gray-500">{template.downloads} 下载</span>
                          </div>
                          <div className="mt-3">
                            <div className="flex flex-wrap gap-1">
                              {template.features.slice(0, 2).map((feature, index) => (
                                <Badge key={index} variant="outline" className="text-xs">
                                  {feature}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* 模板图片定制 */}
              {selectedTemplate && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Image className="h-5 w-5" />
                      模板图片定制
                    </CardTitle>
                    <p className="text-sm text-gray-600">自定义模板中的图片，让网站更符合您的品牌</p>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div>
                        <label className="block text-sm font-medium mb-2">LOGO图片</label>
                        <Input
                          placeholder="https://example.com/logo.png"
                          value={websiteData.companyInfo.logo || ""}
                          onChange={(e) => updateCompanyInfo("logo", e.target.value)}
                        />
                        <p className="text-xs text-gray-500 mt-1">建议尺寸：200x80px，透明背景PNG格式</p>
                      </div>
                      
                      <div>
                        <label className="block text-sm font-medium mb-2">默认产品图片</label>
                        <Input
                          placeholder="https://example.com/default-product.png"
                          value={websiteData.companyInfo.defaultProductImage || ""}
                          onChange={(e) => updateCompanyInfo("defaultProductImage", e.target.value)}
                        />
                        <p className="text-xs text-gray-500 mt-1">建议尺寸：400x300px，用于产品展示</p>
                      </div>
                      
                      <div>
                        <label className="block text-sm font-medium mb-2">默认新闻图片</label>
                        <Input
                          placeholder="https://example.com/default-news.png"
                          value={websiteData.companyInfo.defaultNewsImage || ""}
                          onChange={(e) => updateCompanyInfo("defaultNewsImage", e.target.value)}
                        />
                        <p className="text-xs text-gray-500 mt-1">建议尺寸：600x300px，用于新闻配图</p>
                      </div>
                      
                      <div>
                        <label className="block text-sm font-medium mb-2">默认轮播图</label>
                        <Input
                          placeholder="https://example.com/default-hero.png"
                          value={websiteData.companyInfo.defaultHeroImage || ""}
                          onChange={(e) => updateCompanyInfo("defaultHeroImage", e.target.value)}
                        />
                        <p className="text-xs text-gray-500 mt-1">建议尺寸：1200x600px，用于首页轮播</p>
                      </div>
                    </div>
                    
                    {/* 图片预览 */}
                    <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                      <h4 className="text-sm font-medium mb-3 text-gray-700">图片预览</h4>
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        {[
                          { label: "LOGO", url: websiteData.companyInfo.logo, size: "100x40" },
                          { label: "产品", url: websiteData.companyInfo.defaultProductImage, size: "200x150" },
                          { label: "新闻", url: websiteData.companyInfo.defaultNewsImage, size: "200x100" },
                          { label: "轮播", url: websiteData.companyInfo.defaultHeroImage, size: "200x100" }
                        ].map((item, index) => (
                          <div key={index} className="text-center">
                            <div className="bg-white border rounded-lg p-2 mb-2">
                              {item.url ? (
                                <img
                                  src={item.url}
                                  alt={item.label}
                                  className="w-full h-20 object-cover rounded"
                                  onError={(e) => {
                                    e.currentTarget.src = "https://via.placeholder.com/200x150?text=图片加载失败"
                                  }}
                                />
                              ) : (
                                <div className="w-full h-20 bg-gray-200 rounded flex items-center justify-center">
                                  <Camera className="h-6 w-6 text-gray-400" />
                                </div>
                              )}
                            </div>
                            <div className="text-xs text-gray-600">{item.label}</div>
                            <div className="text-xs text-gray-400">{item.size}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          )}

          {/* Step 2: 公司信息 */}
          {currentStep === 2 && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle>基本信息</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">公司名称 *</label>
                      <Input
                        placeholder="请输入公司名称"
                        value={websiteData.companyInfo.name}
                        onChange={(e) => updateCompanyInfo("name", e.target.value)}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">公司标语</label>
                      <Input
                        placeholder="一句话描述您的公司"
                        value={websiteData.companyInfo.tagline}
                        onChange={(e) => updateCompanyInfo("tagline", e.target.value)}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">所属行业 *</label>
                      <select
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white"
                        value={websiteData.companyInfo.industry}
                        onChange={(e) => updateCompanyInfo("industry", e.target.value)}
                      >
                        <option value="">请选择行业</option>
                        {industries.map(industry => (
                          <option key={industry} value={industry}>{industry}</option>
                        ))}
                      </select>
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">公司描述</label>
                      <Textarea
                        placeholder="详细介绍您的公司..."
                        rows={4}
                        value={websiteData.companyInfo.description}
                        onChange={(e) => updateCompanyInfo("description", e.target.value)}
                      />
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>联系信息</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">邮箱</label>
                      <Input
                        placeholder="contact@company.com"
                        value={websiteData.companyInfo.contact.email}
                        onChange={(e) => updateContactInfo("email", e.target.value)}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">电话</label>
                      <Input
                        placeholder="400-000-0000"
                        value={websiteData.companyInfo.contact.phone}
                        onChange={(e) => updateContactInfo("phone", e.target.value)}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">地址</label>
                      <Input
                        placeholder="公司地址"
                        value={websiteData.companyInfo.contact.address}
                        onChange={(e) => updateContactInfo("address", e.target.value)}
                      />
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>社交媒体</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium mb-2">Facebook</label>
                      <Input
                        placeholder="https://facebook.com/yourcompany"
                        value={websiteData.companyInfo.social.facebook}
                        onChange={(e) => updateSocialInfo("facebook", e.target.value)}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">微博</label>
                      <Input
                        placeholder="https://weibo.com/yourcompany"
                        value={websiteData.companyInfo.social.twitter}
                        onChange={(e) => updateSocialInfo("twitter", e.target.value)}
                      />
                    </div>
                  </CardContent>
                </Card>
              </div>

              <div>
                <Card className="sticky top-4">
                  <CardHeader>
                    <CardTitle>实时预览</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="mb-4">
                      <div className="flex space-x-2">
                        <Button
                          variant={previewMode === "desktop" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("desktop")}
                        >
                          <Monitor className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "tablet" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("tablet")}
                        >
                          <Tablet className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "mobile" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("mobile")}
                        >
                          <Smartphone className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <div className="border rounded-lg overflow-hidden">
                      <WebsitePreview />
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          )}

          {/* Step 3: 内容编辑 */}
          {currentStep === 3 && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <div className="space-y-6">
                <Tabs defaultValue="hero" className="w-full">
                  <TabsList className="grid w-full grid-cols-5">
                    <TabsTrigger value="hero">首页</TabsTrigger>
                    <TabsTrigger value="about">关于</TabsTrigger>
                    <TabsTrigger value="services">服务</TabsTrigger>
                    <TabsTrigger value="products">产品</TabsTrigger>
                    <TabsTrigger value="news">新闻</TabsTrigger>
                  </TabsList>
                  
                  <TabsContent value="hero" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle>首页横幅</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div>
                          <label className="block text-sm font-medium mb-2">主标题 *</label>
                          <Input
                            placeholder="网站主标题"
                            value={websiteData.content.heroTitle}
                            onChange={(e) => updateContent("heroTitle", e.target.value)}
                          />
                        </div>
                        
                        <div>
                          <label className="block text-sm font-medium mb-2">副标题</label>
                          <Textarea
                            placeholder="网站副标题或描述"
                            rows={3}
                            value={websiteData.content.heroSubtitle}
                            onChange={(e) => updateContent("heroSubtitle", e.target.value)}
                          />
                        </div>

                        <div>
                          <div className="flex items-center justify-between mb-2">
                            <label className="block text-sm font-medium">轮播图片</label>
                            <Button onClick={addHeroImage} size="sm">
                              <Plus className="h-4 w-4 mr-1" />
                              添加图片
                            </Button>
                          </div>
                          <div className="space-y-2">
                            {websiteData.content.heroImages.map((image, index) => (
                              <div key={index} className="flex items-center gap-2">
                                <Input
                                  value={image}
                                  onChange={(e) => {
                                    const newImages = [...websiteData.content.heroImages]
                                    newImages[index] = e.target.value
                                    updateContent("heroImages", newImages)
                                  }}
                                  placeholder="图片URL"
                                />
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => removeHeroImage(index)}
                                >
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </div>
                            ))}
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>
                  
                  <TabsContent value="about" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle>关于我们</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div>
                          <label className="block text-sm font-medium mb-2">关于我们 *</label>
                          <Textarea
                            placeholder="详细介绍您的公司、团队、使命和愿景..."
                            rows={8}
                            value={websiteData.content.aboutUs}
                            onChange={(e) => updateContent("aboutUs", e.target.value)}
                          />
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>
                  
                  <TabsContent value="services" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <div className="flex items-center justify-between">
                          <CardTitle>服务项目</CardTitle>
                          <Button onClick={addService} size="sm">
                            <Plus className="h-4 w-4 mr-1" />
                            添加服务
                          </Button>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {websiteData.content.services.map((service, index) => (
                          <div key={index} className="p-4 border rounded-lg">
                            <div className="flex items-center justify-between mb-4">
                              <h4 className="font-medium">服务 {index + 1}</h4>
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => removeService(index)}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </div>
                            <div className="grid grid-cols-1 gap-4">
                              <div>
                                <label className="block text-sm font-medium mb-2">服务名称</label>
                                <Input
                                  placeholder="服务名称"
                                  value={service.title}
                                  onChange={(e) => updateService(index, "title", e.target.value)}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium mb-2">服务描述</label>
                                <Textarea
                                  placeholder="详细描述这项服务..."
                                  rows={3}
                                  value={service.description}
                                  onChange={(e) => updateService(index, "description", e.target.value)}
                                />
                              </div>
                            </div>
                          </div>
                        ))}
                        {websiteData.content.services.length === 0 && (
                          <div className="text-center py-8 text-gray-500">
                            <Building className="h-12 w-12 mx-auto mb-4 opacity-50" />
                            <p>暂无服务项目，点击上方按钮添加</p>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  </TabsContent>

                  <TabsContent value="products" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <div className="flex items-center justify-between">
                          <CardTitle>产品展示</CardTitle>
                          <Button onClick={addProduct} size="sm">
                            <Plus className="h-4 w-4 mr-1" />
                            添加产品
                          </Button>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {websiteData.content.products.map((product, index) => (
                          <div key={index} className="p-4 border rounded-lg">
                            <div className="flex items-center justify-between mb-4">
                              <h4 className="font-medium">产品 {index + 1}</h4>
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => removeProduct(index)}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              <div>
                                <label className="block text-sm font-medium mb-2">产品名称</label>
                                <Input
                                  placeholder="产品名称"
                                  value={product.name}
                                  onChange={(e) => updateProduct(index, "name", e.target.value)}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium mb-2">产品价格</label>
                                <Input
                                  placeholder="¥999"
                                  value={product.price}
                                  onChange={(e) => updateProduct(index, "price", e.target.value)}
                                />
                              </div>
                              <div className="md:col-span-2">
                                <label className="block text-sm font-medium mb-2">产品描述</label>
                                <Textarea
                                  placeholder="详细描述产品功能和特点..."
                                  rows={3}
                                  value={product.description}
                                  onChange={(e) => updateProduct(index, "description", e.target.value)}
                                />
                              </div>
                              <div className="md:col-span-2">
                                <label className="block text-sm font-medium mb-2">产品图片</label>
                                <Input
                                  placeholder="图片URL"
                                  value={product.image}
                                  onChange={(e) => updateProduct(index, "image", e.target.value)}
                                />
                              </div>
                            </div>
                          </div>
                        ))}
                        {websiteData.content.products.length === 0 && (
                          <div className="text-center py-8 text-gray-500">
                            <ShoppingCart className="h-12 w-12 mx-auto mb-4 opacity-50" />
                            <p>暂无产品，点击上方按钮添加</p>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  </TabsContent>

                  <TabsContent value="news" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <div className="flex items-center justify-between">
                          <CardTitle>公司新闻</CardTitle>
                          <Button onClick={addNews} size="sm">
                            <Plus className="h-4 w-4 mr-1" />
                            添加新闻
                          </Button>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {websiteData.content.news.map((news, index) => (
                          <div key={index} className="p-4 border rounded-lg">
                            <div className="flex items-center justify-between mb-4">
                              <h4 className="font-medium">新闻 {index + 1}</h4>
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => removeNews(index)}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              <div>
                                <label className="block text-sm font-medium mb-2">新闻标题</label>
                                <Input
                                  placeholder="新闻标题"
                                  value={news.title}
                                  onChange={(e) => updateNews(index, "title", e.target.value)}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium mb-2">新闻分类</label>
                                <select
                                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white"
                                  value={news.category}
                                  onChange={(e) => updateNews(index, "category", e.target.value)}
                                >
                                  <option value="公司动态">公司动态</option>
                                  <option value="行业资讯">行业资讯</option>
                                  <option value="产品更新">产品更新</option>
                                  <option value="活动通知">活动通知</option>
                                </select>
                              </div>
                              <div className="md:col-span-2">
                                <label className="block text-sm font-medium mb-2">新闻内容</label>
                                <Textarea
                                  placeholder="新闻详细内容..."
                                  rows={4}
                                  value={news.content}
                                  onChange={(e) => updateNews(index, "content", e.target.value)}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium mb-2">发布日期</label>
                                <Input
                                  type="date"
                                  value={news.date}
                                  onChange={(e) => updateNews(index, "date", e.target.value)}
                                />
                              </div>
                              <div>
                                <label className="block text-sm font-medium mb-2">新闻图片</label>
                                <Input
                                  placeholder="图片URL"
                                  value={news.image}
                                  onChange={(e) => updateNews(index, "image", e.target.value)}
                                />
                              </div>
                            </div>
                          </div>
                        ))}
                        {websiteData.content.news.length === 0 && (
                          <div className="text-center py-8 text-gray-500">
                            <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                            <p>暂无新闻，点击上方按钮添加</p>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  </TabsContent>
                </Tabs>
              </div>

              <div>
                <Card className="sticky top-4">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle>实时预览</CardTitle>
                      <div className="flex space-x-2">
                        <Button
                          variant={previewMode === "desktop" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("desktop")}
                        >
                          <Monitor className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "tablet" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("tablet")}
                        >
                          <Tablet className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "mobile" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("mobile")}
                        >
                          <Smartphone className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="border rounded-lg overflow-hidden">
                      <WebsitePreview />
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          )}

          {/* Step 4: 设计定制 */}
          {currentStep === 4 && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle>色彩搭配</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {/* 预设主题 */}
                    <div>
                      <label className="block text-sm font-medium mb-3">预设主题</label>
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                        {[
                          { name: "经典蓝", primary: "#3B82F6", secondary: "#1E40AF" },
                          { name: "商务绿", primary: "#10B981", secondary: "#059669" },
                          { name: "优雅紫", primary: "#8B5CF6", secondary: "#7C3AED" },
                          { name: "活力橙", primary: "#F59E0B", secondary: "#D97706" },
                          { name: "沉稳灰", primary: "#6B7280", secondary: "#4B5563" },
                          { name: "热情红", primary: "#EF4444", secondary: "#DC2626" },
                          { name: "清新青", primary: "#06B6D4", secondary: "#0891B2" },
                          { name: "温暖棕", primary: "#A16207", secondary: "#92400E" }
                        ].map((theme, index) => (
                          <div
                            key={index}
                            onClick={() => {
                              updateDesign("primaryColor", theme.primary)
                              updateDesign("secondaryColor", theme.secondary)
                            }}
                            className="cursor-pointer p-3 border rounded-lg hover:shadow-md transition-shadow"
                          >
                            <div className="flex space-x-1 mb-2">
                              <div 
                                className="w-4 h-4 rounded" 
                                style={{ backgroundColor: theme.primary }}
                              ></div>
                              <div 
                                className="w-4 h-4 rounded" 
                                style={{ backgroundColor: theme.secondary }}
                              ></div>
                            </div>
                            <div className="text-xs text-center text-gray-600">{theme.name}</div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* 自定义颜色 */}
                    <div>
                      <label className="block text-sm font-medium mb-2">自定义主色调</label>
                      <div className="flex items-center space-x-4">
                        <input
                          type="color"
                          value={websiteData.design.primaryColor}
                          onChange={(e) => updateDesign("primaryColor", e.target.value)}
                          className="w-12 h-12 rounded border"
                        />
                        <Input
                          value={websiteData.design.primaryColor}
                          onChange={(e) => updateDesign("primaryColor", e.target.value)}
                          placeholder="#3B82F6"
                        />
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium mb-2">自定义辅助色</label>
                      <div className="flex items-center space-x-4">
                        <input
                          type="color"
                          value={websiteData.design.secondaryColor}
                          onChange={(e) => updateDesign("secondaryColor", e.target.value)}
                          className="w-12 h-12 rounded border"
                        />
                        <Input
                          value={websiteData.design.secondaryColor}
                          onChange={(e) => updateDesign("secondaryColor", e.target.value)}
                          placeholder="#10B981"
                        />
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>字体选择</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div>
                      <label className="block text-sm font-medium mb-2">字体系列</label>
                      <select
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white"
                        value={websiteData.design.fontFamily}
                        onChange={(e) => updateDesign("fontFamily", e.target.value)}
                      >
                        {fontFamilies.map(font => (
                          <option key={font.name} value={font.name}>{font.display}</option>
                        ))}
                      </select>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>布局风格</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-2 gap-4">
                      {layoutStyles.map((style) => {
                        const IconComponent = style.icon
                        return (
                          <Card 
                            key={style.id}
                            className={`cursor-pointer transition-all hover:shadow-md ${
                              websiteData.design.layoutStyle === style.id ? 'ring-2 ring-blue-500 bg-blue-50' : ''
                            }`}
                            onClick={() => updateDesign("layoutStyle", style.id)}
                          >
                            <CardContent className="p-4 text-center">
                              <IconComponent className="h-8 w-8 mx-auto mb-2 text-blue-500" />
                              <h3 className="font-medium">{style.name}</h3>
                            </CardContent>
                          </Card>
                        )
                      })}
                    </div>
                  </CardContent>
                </Card>
              </div>

              <div>
                <Card className="sticky top-4">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle>设计预览</CardTitle>
                      <div className="flex space-x-2">
                        <Button
                          variant={previewMode === "desktop" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("desktop")}
                        >
                          <Monitor className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "tablet" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("tablet")}
                        >
                          <Tablet className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "mobile" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("mobile")}
                        >
                          <Smartphone className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="border rounded-lg overflow-hidden">
                      <WebsitePreview />
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          )}

          {/* Step 5: 预览发布 */}
          {currentStep === 5 && (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
              <div className="lg:col-span-2">
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle>网站预览</CardTitle>
                      <div className="flex space-x-2">
                        <Button
                          variant={previewMode === "desktop" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("desktop")}
                        >
                          <Monitor className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "tablet" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("tablet")}
                        >
                          <Tablet className="h-4 w-4" />
                        </Button>
                        <Button
                          variant={previewMode === "mobile" ? "default" : "outline"}
                          size="sm"
                          onClick={() => setPreviewMode("mobile")}
                        >
                          <Smartphone className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="border rounded-lg overflow-hidden">
                      <WebsitePreview />
                    </div>
                  </CardContent>
                </Card>
              </div>

              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle>发布选项</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <Button 
                      onClick={publishWebsite}
                      disabled={loading}
                      className="w-full bg-blue-500 hover:bg-blue-600"
                    >
                      {loading ? (
                        <>
                          <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                          发布中...
                        </>
                      ) : (
                        <>
                          <Globe className="w-4 h-4 mr-2" />
                          立即发布
                        </>
                      )}
                    </Button>
                    
                    <Button 
                      variant="outline" 
                      onClick={downloadWebsite}
                      className="w-full"
                    >
                      <Download className="w-4 h-4 mr-2" />
                      下载代码
                    </Button>
                    
                    <Button 
                      variant="outline" 
                      onClick={sharePreview}
                      className="w-full"
                    >
                      <Share2 className="w-4 h-4 mr-2" />
                      分享预览
                    </Button>

                    {publishedUrl && (
                      <div className="mt-4 p-3 bg-green-50 border border-green-200 rounded-lg">
                        <div className="flex items-center space-x-2 text-green-800">
                          <CheckCircle className="w-4 h-4" />
                          <span className="text-sm font-medium">发布成功！</span>
                        </div>
                        <div className="mt-2">
                          <a 
                            href={publishedUrl} 
                            target="_blank" 
                            rel="noopener noreferrer"
                            className="text-sm text-blue-600 hover:underline break-all"
                          >
                            {publishedUrl}
                          </a>
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>网站统计</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">总页面数</span>
                      <span className="font-medium">1</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">服务项目</span>
                      <span className="font-medium">{websiteData.content.services.length}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">产品数量</span>
                      <span className="font-medium">{websiteData.content.products.length}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">新闻文章</span>
                      <span className="font-medium">{websiteData.content.news.length}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">轮播图片</span>
                      <span className="font-medium">{websiteData.content.heroImages.length}</span>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>后续服务</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="flex items-center space-x-2 text-sm">
                      <Shield className="w-4 h-4 text-green-500" />
                      <span>免费SSL证书</span>
                    </div>
                    <div className="flex items-center space-x-2 text-sm">
                      <BarChart3 className="w-4 h-4 text-blue-500" />
                      <span>流量统计分析</span>
                    </div>
                    <div className="flex items-center space-x-2 text-sm">
                      <Search className="w-4 h-4 text-purple-500" />
                      <span>SEO优化服务</span>
                    </div>
                    <div className="flex items-center space-x-2 text-sm">
                      <Headphones className="w-4 h-4 text-orange-500" />
                      <span>技术支持</span>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          )}

          {/* Loading State */}
          {loading && currentStep === 4 && (
            <Card>
              <CardContent className="p-8 text-center">
                <div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-cyan-600 rounded-full flex items-center justify-center mx-auto mb-4">
                  <Rocket className="w-8 h-8 text-white animate-pulse" />
                </div>
                <h3 className="text-xl font-semibold mb-2">正在生成网站...</h3>
                <p className="text-gray-600 mb-6">正在应用您的设计和内容设置</p>
                <Progress value={66} className="w-full max-w-md mx-auto" />
                <p className="text-sm text-gray-500 mt-2">预计需要2-3分钟</p>
              </CardContent>
            </Card>
          )}

          {/* 操作按钮 */}
          {currentStep < 5 && (
            <div className="flex justify-between pt-8 border-t">
              <Button
                variant="outline"
                onClick={prevStep}
                disabled={currentStep === 1}
              >
                上一步
              </Button>
              
              {currentStep === 4 ? (
                <Button
                  onClick={generateWebsite}
                  disabled={!validateStep(currentStep) || loading}
                  className="bg-blue-500 hover:bg-blue-600"
                >
                  {loading ? (
                    <>
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                      生成中...
                    </>
                  ) : (
                    <>
                      <Rocket className="w-4 h-4 mr-2" />
                      生成网站
                    </>
                  )}
                </Button>
              ) : (
                <Button
                  onClick={nextStep}
                  disabled={!validateStep(currentStep)}
                  className="bg-blue-500 hover:bg-blue-600"
                >
                  下一步
                </Button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}